/*******************************************************************************
 * @project: aohuproject
 * @package: com.aohua.erp
 * @file: ExportItemsIntoERPAction.java
 * @author: fionn
 * @created: 2015年8月13日
 * @purpose:
 * 
 * @version: 1.0
 * 
 * 
 * Copyright 2015 HAND All rights reserved.
 ******************************************************************************/
package com.aohua.erp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.agile.api.APIException;
import com.agile.api.ChangeConstants;
import com.agile.api.IAgileSession;
import com.agile.api.ICell;
import com.agile.api.IChange;
import com.agile.api.IDataObject;
import com.agile.api.IItem;
import com.agile.api.INode;
import com.agile.api.IRow;
import com.agile.api.ITable;
import com.agile.api.ITwoWayIterator;
import com.agile.api.ItemConstants;
import com.agile.px.ActionResult;
import com.agile.px.EventActionResult;
import com.agile.px.ICustomAction;
import com.agile.px.IEventAction;
import com.agile.px.IEventInfo;
import com.agile.px.IWFChangeStatusEventInfo;
import com.hand.agile.utils.CellUtils;

/**
 * @author fionn
 *
 */
public class ExportItemsIntoERPAction implements ICustomAction, IEventAction {

    private static Logger log = Logger.getLogger(ExportItemsIntoERPAction.class);
    
    /* (non-Javadoc)
     * @see com.agile.px.IEventAction#doAction(com.agile.api.IAgileSession, com.agile.api.INode, com.agile.px.IEventInfo)
     */
    @Override
    public EventActionResult doAction(IAgileSession session, INode arg1,
            IEventInfo arg2) {
        EventActionResult result = null;
        try {
            session.disableAllWarnings();
            IWFChangeStatusEventInfo eventInfo = (IWFChangeStatusEventInfo) arg2;
            IChange change = (IChange)eventInfo.getDataObject();
            exportItemsAndBOMsIntoERP(change);
            result = new EventActionResult(arg2, new ActionResult(ActionResult.STRING, "成功导入ERP中间表."));
        } catch (Exception e) {
            result = new EventActionResult(arg2, new ActionResult(ActionResult.EXCEPTION, e));
            log.error(e);
            e.printStackTrace(System.out);
        } finally {
            try {
                session.enableAllWarnings();
            } catch (APIException e) {
                e.printStackTrace(System.out);
            }
        }
        return result;
    }

    /* (non-Javadoc)
     * @see com.agile.px.ICustomAction#doAction(com.agile.api.IAgileSession, com.agile.api.INode, com.agile.api.IDataObject)
     */
    @Override
    public ActionResult doAction(IAgileSession session, INode arg1,
            IDataObject arg2) {
        ActionResult result = null;
        try {
            session.disableAllWarnings();
            IChange change = (IChange) arg2;
            exportItemsAndBOMsIntoERP(change);
            result = new ActionResult(ActionResult.STRING, "成功导入ERP中间表.");
        } catch (Exception e) {
            result = new ActionResult(ActionResult.EXCEPTION, e);
            log.error(e);
            e.printStackTrace(System.out);
        } finally {
            try {
                session.enableAllWarnings();
            } catch (APIException e) {
                e.printStackTrace(System.out);
            }
        }
        return result;
    }

    private void exportItemsAndBOMsIntoERP(IChange change) throws APIException {
        DBService dbservice = null;
        try {
            String ecoNumber = change.getName();
            // for items
            List<ERPItemPayload> itemPayloads = new ArrayList<ERPItemPayload>();
            // for boms
            ExportBOMsIntoERPService bomService = new ExportBOMsIntoERPService();
            List<ERPBomPayload> bomPayloads = new ArrayList<ERPBomPayload>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String pid = sdf.format(new Date());
            List<String> exportItems = new ArrayList<String>();
            
            ITable table = change.getTable(ChangeConstants.TABLE_AFFECTEDITEMS);
            ITwoWayIterator it = table.getTableIterator();//table.getReferentIterator();
            while(it.hasNext()) {
                IRow row = (IRow)it.next();
                IItem item = (IItem)row.getReferent();
                ERPItemPayload itemPayload = getERPPayload(item);
//                变更号
                itemPayload.setEcoNumber(ecoNumber);
                // 新版本
                ICell cell = row.getCell(ChangeConstants.ATT_AFFECTED_ITEMS_OLD_REV);
                itemPayload.setOldRev(CellUtils.getCellStringValue(cell));
//                老版本
                cell = row.getCell(ChangeConstants.ATT_AFFECTED_ITEMS_NEW_REV);
                itemPayload.setNewRev(CellUtils.getCellStringValue(cell));
                itemPayloads.add(itemPayload);
                bomService.extractBomPayload(row, pid, bomPayloads, exportItems);
            }
            
            dbservice = new DBService("/database.properties");
            dbservice.connect();
            dbservice.writePayload(itemPayloads);
            dbservice.writeBOMPayload(exportItems, bomPayloads);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace(System.out);
        } finally {
            if(dbservice != null) {
                dbservice.close();
            }
        }
    }
    
    private ERPItemPayload getERPPayload(IItem item) throws APIException {
        log.debug("Import to ERP: " + item.getName());
        ERPItemPayload payload = new ERPItemPayload();
        // type
        ICell cell = item.getCell(ItemConstants.ATT_TITLE_BLOCK_PART_TYPE);
        payload.setType(CellUtils.getCellStringValue(cell));
        // description
        cell = item.getCell(ItemConstants.ATT_TITLE_BLOCK_DESCRIPTION);
        payload.setDescription(CellUtils.getCellStringValue(cell));
        // category
        cell = item.getCell(new Integer(ItemConstants.ATT_TITLE_BLOCK_PART_CATEGORY));
        payload.setCategory(CellUtils.getCellStringValue(cell));
        // specification
        cell = item.getCell(ItemConstants.ATT_PAGE_TWO_MULTITEXT31);
        payload.setSpecification(CellUtils.getCellStringValue(cell));
        // status
        cell = item.getCell(ItemConstants.ATT_TITLE_BLOCK_LIFECYCLE_PHASE);
        payload.setStatus(CellUtils.getCellStringValue(cell));
        // unit
        cell = item.getCell(ItemConstants.ATT_PAGE_TWO_LIST11);
        payload.setUnit(CellUtils.getCellStringValue(cell));
        // feature
        cell = item.getCell(ItemConstants.ATT_PAGE_TWO_LIST12);
        String feature = CellUtils.getCellStringValue(cell);
        payload.setFeature(feature);
        
        String fix = (feature != null && (feature.contains("外协") || feature.contains("外购"))) ? "G" : "M"; 
        // 
        if("G".equals(fix)) {
            cell = item.getCell(new Integer(ItemConstants.ATT_PAGE_TWO_LIST16));
            String f2 = CellUtils.getCellStringValue(cell);
            fix = "是".equals(f2) ? "W" : fix; // 委外加工
        }
        // orgnumber
        payload.setOrgName(item.getName());
        // number
        payload.setNumber(item.getName()+fix);
        return payload;
    }
}
